package com.googlecode.maratische.google.model;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import javax.swing.SwingUtilities;

import be.lechtitseb.google.reader.api.core.GoogleReader;
import be.lechtitseb.google.reader.api.model.exception.GoogleReaderException;
import be.lechtitseb.google.reader.api.model.feed.FeedDescriptor;
import be.lechtitseb.google.reader.api.model.opml.Outline;
import be.lechtitseb.google.reader.api.util.GoogleReaderUtil;

import com.googlecode.maratische.google.BaseException;
import com.googlecode.maratische.google.CommandProcessor;
import com.googlecode.maratische.google.DaoAction;
import com.googlecode.maratische.google.MainController;

public class CommandUpdateMainMenu extends Command {
//	private static Logger logger = Logger.getLogger(CommandUpdateMainMenu.class.getName());

	protected CommandUpdateMainMenu() {
	}

	@Override
	public String getType() {
		return Commands.UpdateMainMenu.toString();
	}

	@Override
	public Integer getPriority() {
		return 2;
	}

	@Override
	public boolean execute(final DaoAction daoAction) throws BaseException, GoogleReaderException, SQLException {
		GoogleReader googleReader = getGoogleReader(daoAction);
		String xmlContent = googleReader.getApi().getFeedsWithUnreadItems();// eedItems("feed/http://auto.lenta.ru/l/r/EX/yandexfull.rss");
		List<FeedDescriptor> feeds = GoogleReaderUtil.getFeedDescriptorsFromFeedsWithUnreadItemsXml(xmlContent);
		List<Outline> subscriptions = GoogleReaderUtil.parseOPMLSubscriptions(daoAction.getGoogleReader().exportSubscriptionsToOPML());
		for (Outline outline : subscriptions) {
			List<Command> commands = daoAction.getFeedDao().saveAndUpdateOutline(outline, feeds, 0);
			for (Command command : commands) {
				daoAction.getCommandDao().save(command);
			}
		}
		// daoAction.mainFrame.updateFeedMenu();
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				MainController.getMainController().updateFeedMenu();
			}
		});
		//показываем спец меню, описывающие новые ленты
		checkHaveAddedFeed(daoAction);
		//удаление старых, давно прочитанных
		CommandSearchItemForDelete command = (CommandSearchItemForDelete) Command.createCommand(Commands.SearchItemForDelete);
		daoAction.getCommandDao().save(command);
		//запуск спам фильтров
		List<Spam> spams = daoAction.getSpamDao().list();
		for (Spam spam : spams) {
			CommandSearchSpammedItem commandSearchSpammedItem = (CommandSearchSpammedItem)Command.createCommand(Commands.SearchSpammedItem);
			commandSearchSpammedItem.setInteger1(spam.getId());
			CommandProcessor.getCommandProcessor().createCommand(commandSearchSpammedItem);
		}
		
		return true;
	}
	
	private void checkHaveAddedFeed(DaoAction daoAction) throws SQLException, BaseException {
		/**
		 * TODO изменить на спец запрос
		 */
		List<Feed> feeds = daoAction.getFeedDao().list();
		List<Feed> newFeeds = new ArrayList<Feed>();
		for (Feed feed : feeds) {
			if (feed.getOfflineSupport() == null && feed.isFolder() == false && feed.getUnreadItems()>0) {
				newFeeds.add(feed);
			}
		}
//		logger.info("new feeds " + newFeeds.size());
		if (newFeeds.size()>0) {
			MainController.getMainController().showInfWindowCheckNewFeeds(newFeeds);
		}
	}

}
